﻿using System.Threading.Tasks;

using Common.Enums;

using GameCommon.Base;
using GameCommon.Manager;

using GameNetwork;
using GameNetwork.Interfaces;

using Microsoft.Xna.Framework;

using GlobalServices = GameCommon.Services.Service;

namespace Menu.Screens.LoadScreen
{
    public class LoadScreen : ScreenBase
    {
        private ScreenEnum nextScreen;

        private Task loadingTask;

        private IMenuNetwork network;

        private bool ready;

        public LoadScreen(IScreenChanger changer, object argument)
            : base(changer, argument)
        {
        }

        public override ScreenEnum Screen
        {
            get
            {
                return ScreenEnum.LoadScreen;
            }
        }

        public override void Initialize()
        {
            base.Initialize();

            if (this.Argument == null)
            {
                return;
            }

            this.network = NetworkDistributor.GetMenuNetwork();
            this.nextScreen = this.Argument is ScreenEnum ? (ScreenEnum)this.Argument : ScreenEnum.None;

            this.loadingTask = new Task(this.LoadData);
            this.loadingTask.Start();
        }

        public override void LoadContent()
        {
            base.LoadContent();

            this.Components = MenuLoader.Get(this.Screen);
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);


            if (this.nextScreen == ScreenEnum.GameBoard)
            {
                if (this.loadingTask.IsCompleted && !this.ready)
                {
                    this.network.Ready();
                    this.ready = true;
                }

                if (this.ready && this.network.IsGameStarted)
                {
                    this.RemoveScreen(this.Screen);
                    this.AddScreen(this.nextScreen);
                }
            }
        }

        private void LoadData()
        {
            if (this.nextScreen == ScreenEnum.GameBoard)
            {
                foreach (var file in GlobalServices.LoadingService.GetBoardTextures())
                {
                    Managers.ContentManager.LoadTexture(file);
                }
            }

            if (this.nextScreen == ScreenEnum.Splash)
            {
                foreach (var file in GlobalServices.LoadingService.GetMenuTextures())
                {
                    Managers.ContentManager.LoadTexture(file);
                }
            }
        }
    }
}